package com.threadPool.pool;

import com.threadPool.enums.ExecutorType;
import com.threadPool.enums.RejectedPolicy;
import com.threadPool.pool.MyThreadPool;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;

public class DynamicThreadPoolManager {
    private static volatile DynamicThreadPoolManager instance;
    private BaseThreadPool threadPool;
    private Properties properties;
    private DynamicThreadPoolManager() {
        // 使用 ClassLoader 加载资源文件
        try {
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("dynamicTP.properties");
            if (inputStream == null) {
                throw new RuntimeException("dynamicTP.properties 文件未找到！");
            }
            properties = new Properties();
            properties.load(inputStream);
        } catch (Exception e) {
            throw new RuntimeException("Failed to load configuration file", e);
        }

        long timeOut = Long.parseLong(properties.getProperty("dynamicTP.timeOut", "60"));
        TimeUnit timeOutUnit = TimeUnit.valueOf(properties.getProperty("dynamicTP.timeOutUnit", "SECONDS"));
        int coreThreadSize = Integer.parseInt(properties.getProperty("dynamicTP.coreThreadSize", "5"));
        int workerThreadSize = Integer.parseInt(properties.getProperty("dynamicTP.workerThreadSize", "10"));
        int taskQueueSize = Integer.parseInt(properties.getProperty("dynamicTP.taskQueueSize", "100"));
        RejectedPolicy rejectedPolicy = RejectedPolicy.valueOf(properties.getProperty("dynamicTP.rejectedPolicy", "ABORT"));
        String executorType = properties.getProperty("dynamicTP.executorType", "COMMON");
        threadPool = threadPoolCreator(timeOut, timeOutUnit, coreThreadSize, workerThreadSize, taskQueueSize, rejectedPolicy,executorType);
//        myThreadPool = new MyThreadPool(timeOut, timeOutUnit, coreThreadSize, workerThreadSize, taskQueueSize, rejectedPolicy);
    }

    private BaseThreadPool threadPoolCreator(long timeOut, TimeUnit timeOutUnit, int coreThreadSize, int workerThreadSize, int taskQueueSize, RejectedPolicy rejectedPolicy, ExecutorType executorType) {
        switch (executorType) {
            case COMMON:
                return new CommonThreadPool(timeOut, timeOutUnit, coreThreadSize, workerThreadSize, taskQueueSize, rejectedPolicy);
            default:
                throw new IllegalArgumentException("Unsupported ExecutorType: " + executorType);
        }
    }

    public static DynamicThreadPoolManager getInstance() {
        if (instance == null) {
            synchronized (DynamicThreadPoolManager.class) {
                if (instance == null) {
                    instance = new DynamicThreadPoolManager();
                }
            }
        }
        return instance;
    }

    public BaseThreadPool getMyThreadPool() {
        return threadPool;
    }
}